package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.AppVersion;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.service.Net_Service;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CacheManager;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.jdy.haoduoai.widget.CustomUpdateDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

//import com.jdy.haoduoai.R;

public class SettingActivity extends BaseActivity implements OnClickListener {
  // public static final int FLOAT_WINDOW_VISIBLE = 403;
  //
  // public static final int FLOAT_WINDOW_GONE = 404;

  private boolean mFloatWindowVisible = true;

  @InjectView(id = R.id.setting_clearcache_btn, click = true)
  private View setting_clearcache_btn;

  @InjectView(id = R.id.tv_cachesize)
  private TextView tv_cachesize;

  @InjectView(id = R.id.setting_clear_template_btn, click = true)
  private Button setting_clear_template_btn;

//  @InjectView(id = R.id.btn_opexplain, click = true)
//  private Button btn_opexplain;

  @InjectView(id = R.id.setting_feedback_btn, click = true)
  private Button setting_feedback_btn;

//  @InjectView(id = R.id.btn_customservice, click = true)
//  private Button btn_customservice;

  @InjectView(id = R.id.setting_about_btn, click = true)
  private Button setting_about_btn;

//  @InjectView(id = R.id.setting_update_btn, click = true)
//  private View setting_update_btn;

//  @InjectView(id = R.id.currentSoftVersionTextView)
//  private TextView currentSoftVersionTextView;

  @InjectView(id = R.id.btn_faq, click = true)
  private Button btn_faq;

  @InjectView(id = R.id.float_window_checkbox, click = true)
  private CheckBox mFloatWindowCheckBox;

  @InjectView(id = R.id.exitRelativeLayout, click = true)
  private View exitRelativeLayout;

  @InjectView(id = R.id.connectinnerip_onoff)
  private CheckBox connectinnerip_onoff;

  CustomUpdateDialog mProgressDialog;

  private int totalFileLen, downloadLen;

  BroadcastReceiver broadcastReceiver;

  String netSpeed = "";

  public static final String BROADCAST_ACTIONEXITxxj ="exitJZD";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting_layout);
    setTitle("设置");

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.jdy.haoduoai.speed");
    broadcastReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        netSpeed = intent.getStringExtra("speed");
      }
    };
    registerReceiver(broadcastReceiver, intentFilter);

    // 版本
    PackageInfo pInfo;
//    try {
//      pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
//      currentSoftVersionTextView.setText(pInfo.versionName);
//    } catch (NameNotFoundException e) {
//      e.printStackTrace();
//    }

    // 缓存
    try {
      String cacheSize = CacheManager.getCacheSize(this);
      tv_cachesize.setText(cacheSize);
    } catch (Exception e) {
      e.printStackTrace();
    }

    exitRelativeLayout.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            SettingActivity.this).setMessage("确定要退出小小金吗？")
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
//                doExitApp();
                //返回管理端
                exitxxj();
                finish();
              }
            });
        if (!isFinishing()) {
          cdb.create().show();
        }
      }
    });

    boolean isConnInnerIp = LePreference.getInstance().getBoolean(
        "connectinnerip", false);

    connectinnerip_onoff.setChecked(isConnInnerIp);

    connectinnerip_onoff
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView,
              boolean isChecked) {

            connectinnerip_onoff.setChecked(isChecked);
            LePreference.getInstance().save("connectinnerip", isChecked);

          }
        });
  }

  //退出小小金
  private void exitxxj() {

    Intent broadCastIntent = new Intent();
    broadCastIntent.setAction(BROADCAST_ACTIONEXITxxj);
    sendBroadcast(broadCastIntent);

  }

  @Override
  protected void onDestroy() {
    if (broadcastReceiver != null) {
      unregisterReceiver(broadcastReceiver);
      broadcastReceiver = null;
    }

    super.onDestroy();
  }

  private void logout() {
    final LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

    if (lu != null) {
      new CustomAsyncTask(this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          if (result.isSuccess()) {

          }
        }

        @Override
        public ResponseResult doInbackground(Activity activity) {

          HashMap<String, Object> param_ = new HashMap<String, Object>();
          param_.put(HttpUtils.TAG_SNO_I, lu.sno);
          param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

          return HttpUtils.startRequest(HttpUtils.API_URL
              + "/api/2.0/member/logout", param_, HttpUtils.TAG_POST_REQUEST);
        }
      }).execute("获取信息失败，请检查网络连接!");
    }
  }

  private void doExitApp() {

    logout();

    // clear cache
    LePreference.getInstance().delete(LePreference.PREFERNCE_TELLSTORY_CACHE);
    LePreference.getInstance().delete(LePreference.PREFERNCE_PUSHSTORY_CACHE);
    LePreference.getInstance().delete(LePreference.PREFERNCE_PUSHSLIDE_CACHE);
    LePreference.getInstance().delete(LePreference.PREFERNCE_SHARERANK_CACHE);
    LePreference.getInstance()
        .delete(LePreference.PREFERNCE_LAST_PUSHTIMESTAMP);
    LePreference.getInstance().delete(LePreference.PREFERNCE_NEXT_TIMESTAMP);
    LePreference.getInstance().delete("openradiodetailcount");
    LePreference.getInstance().delete("opensuitforbabydetailcount");

    LePreference.getInstance().delete("floatWindowVisibility");

    LePreference.getInstance().delete("playmode");

    // stopService(new Intent(this, LeSocketManagerService.class));

     SocketThreadManager.releaseInstance();
   //  SocketThreadManager.getInstance().releaseInstance();

    // Intent notificationIntent = new Intent(this, DeviceMonitorService.class);
    // notificationIntent.putExtra("stop_service", true);
    // notificationIntent.putExtra("root_visiblity", View.GONE);
    // stopService(notificationIntent);

    Intent logoutIntent = new Intent("com.jdy.haoduoai.activity.logout");
    sendBroadcast(logoutIntent);

    LeConfig.isLogin = false;
    LeConfig.isDeviceActivated = false;
    LeConfig.isDeviceBinded = false;
    LeConfig.isInfoFilled = false;
    // /Config.isReady = false;

    File dir = getFilesDir();
    File file1 = new File(dir, Constant.TELL_STORY_SERACH_FILE);
    file1.delete();
    File file2 = new File(dir, Constant.PUSH_STORY_SERACH_FILE);
    file2.delete();

    ACache pCache = ACache.get(this);
    pCache.clear();

    LeXiaoXiaoBanApp.getInstance().forgetUser();

    Intent intent = new Intent(this, LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);

  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    // case R.id.btn_faq:
    // startActivity(new Intent(this, NormalQuestionActivity.class));
    // break;
    case R.id.setting_clearcache_btn:
      // startActivity(new Intent(this, SettingClearcacheActivity.class));
      clearCache();
      break;
//    case R.id.btn_opexplain:
//      Intent intent1 = new Intent(this, TestSpecificationActivity.class);
//      intent1.putExtra("title", "使用说明");
//      intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//      startActivity(intent1);
//      break;
    case R.id.setting_clear_template_btn:
      clearTemplateCache();
      break;
    case R.id.setting_feedback_btn:
      startActivity(new Intent(this, SettingFeedbackActivity.class));
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
//    case R.id.btn_customservice:
//      startActivity(new Intent(this, SettingCustomServiceActivity.class));
//      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//      break;
    case R.id.setting_about_btn:
      startActivity(new Intent(this, SettingAboutActivity.class));
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
//    case R.id.setting_update_btn:
//
//     checkForNewestVersion();

//      break;
    default:
      break;
    }
  }

  private void checkForNewestVersion() {
    showloading("");

    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        dismissLoading();

        if (result.isSuccess()) {
          AppVersion av = JsonSerializer.getInstance().deserialize(result.data,
              AppVersion.class);

          if (av != null) {
            int currentAppVersion;
            try {
              currentAppVersion = Integer.valueOf(getPackageManager()
                  .getPackageInfo(getPackageName(), 0).versionName.replaceAll(
                  "\\D+", ""));
              int newestAppVersion = Integer.valueOf(av.value.replaceAll(
                  "\\D+", ""));

              if (newestAppVersion > currentAppVersion) {
                startDownloadNewestVersion(av.value, av.download_url, av.desc);
              } else {
                Toast.makeText(getApplicationContext(), "当前已是最新版本",
                    Toast.LENGTH_SHORT).show();
              }

            } catch (NumberFormatException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (NameNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

          }
        } else {
          Toast.makeText(getApplicationContext(), result.data,
              Toast.LENGTH_SHORT).show();
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_PLATFORM_I, "android");
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/app/version", param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  CustomUpdateDialog.Builder bbbb;
  DownloadTask mDownloadTask;

  private void startDownloadNewestVersion(final String remoteVersion,
      final String downloadUrl, String desc) {
    boolean usingGprs = isUsingGPRSConnection();
    if (usingGprs) {
      Toast.makeText(getApplicationContext(), "您当前正在使用移动流量!",
          Toast.LENGTH_SHORT).show();
    }

    bbbb = null;
    bbbb = new CustomUpdateDialog.Builder(this).setTitle("发现新版本")
        .setMessage("更新内容:\n" + desc)
        .setNegativeButton("", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();

            stopService(new Intent(SettingActivity.this, Net_Service.class));

            if (mDownloadTask != null) {
              mDownloadTask.cancel(true);
              mDownloadTask = null;
            }

            if (mProgressDialog != null) {
              mProgressDialog.dismiss();
              mProgressDialog = null;
            }

          }
        }).setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            // dialog.dismiss();

            if (mProgressDialog == null) {
              mProgressDialog = bbbb.create();
              mProgressDialog.setCancelable(true);
              mProgressDialog.setCanceledOnTouchOutside(false);
            }

            startService(new Intent(SettingActivity.this, Net_Service.class));

            if (bbbb != null) {
              if (bbbb.umeng_update_frame != null) {
                bbbb.umeng_update_frame
                    .setBackgroundResource(R.drawable.update_dlg_bg2);
              }

              if (bbbb.pb_day != null) {

                bbbb.pb_day.setVisibility(View.VISIBLE);
              }

              if (bbbb.tv_filetip != null) {
                bbbb.tv_filetip.setVisibility(View.VISIBLE);
              }

              if (bbbb.tv_netspeed != null) {
                bbbb.tv_netspeed.setVisibility(View.VISIBLE);
              }

              if (bbbb.tv_wifi != null) {
                bbbb.tv_wifi.setVisibility(View.VISIBLE);
              }
            }

            mDownloadTask = new DownloadTask(SettingActivity.this);
            mDownloadTask.execute(downloadUrl, remoteVersion);

            mProgressDialog
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                  @Override
                  public void onCancel(DialogInterface dialog) {

                    if (mDownloadTask != null) {
                      mDownloadTask.cancel(true);
                      mDownloadTask = null;
                    }

                    if (mProgressDialog != null) {
                      mProgressDialog.dismiss();
                      mProgressDialog = null;
                    }

                  }
                });
          }
        });

    if (!isFinishing()) {
      if (mProgressDialog == null) {
        mProgressDialog = bbbb.create();
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
      }
      mProgressDialog.show();

      if (bbbb != null) {
        if (bbbb.pb_day != null) {
          bbbb.pb_day.setVisibility(View.GONE);
        }

        if (bbbb.tv_filetip != null)
          bbbb.tv_filetip.setVisibility(View.GONE);

        if (bbbb.tv_netspeed != null) {
          bbbb.tv_netspeed.setVisibility(View.GONE);
        }

        if (bbbb.tv_wifi != null) {
          bbbb.tv_wifi.setVisibility(View.GONE);
        }

        if (bbbb.tv_version != null) {
          bbbb.tv_version.setText("V" + remoteVersion);
        }
      }
    }
  }

  private boolean isUsingGPRSConnection() {
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
      if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
          haveConnectedMobile = true;
    }
    return haveConnectedMobile;
  }

  private class DownloadTask extends AsyncTask<String, Integer, String> {

    private final Context context;

    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
      this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
      InputStream input = null;
      OutputStream output = null;
      HttpURLConnection connection = null;
      try {
        URL url = new URL(sUrl[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
          return "Server returned HTTP " + connection.getResponseCode() + " "
              + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        totalFileLen = fileLength;

        // download the file
        input = connection.getInputStream();
        String downloadPath = Environment.getExternalStorageDirectory()
            .getAbsolutePath();
        downloadPath += "/download/" + "com.jdy.haoduoai" + sUrl[1]
            + ".apk";

        File mFolder = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/download/");
        if (!mFolder.exists()) {
          mFolder.mkdir();
        }

        output = new FileOutputStream(downloadPath);

        byte data[] = new byte[4096];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
          // allow canceling with back button
          if (isCancelled()) {
            input.close();
            return null;
          }
          total += count;

          downloadLen = (int) total;
          // publishing the progress....
          if (fileLength > 0) // only if total length is known
            publishProgress((int) (total * 100 / fileLength));
          output.write(data, 0, count);
        }
        return downloadPath;
      } catch (Exception e) {
        return e.toString();
      } finally {
        try {
          if (output != null)
            output.close();
          if (input != null)
            input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
          connection.disconnect();
      }
    }

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      // take CPU lock to prevent CPU from going off if the user
      // presses the power button during download
      PowerManager pm = (PowerManager) context
          .getSystemService(Context.POWER_SERVICE);
      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass()
          .getName());
      mWakeLock.acquire();
      if (!isFinishing()) {
        mProgressDialog.show();
      }
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
      super.onProgressUpdate(progress);
      // if we get here, length is known, now set indeterminate to false
      // mProgressDialog.setIndeterminate(false);
      bbbb.pb_day.setMax(100);
      bbbb.pb_day.setProgress(progress[0]);

      bbbb.tv_netspeed.setText(netSpeed);
      bbbb.tv_filetip.setText(Html.fromHtml("<font color =\"#4fbafc\">"
          + android.text.format.Formatter.formatFileSize(SettingActivity.this,
              downloadLen)
          + "/"
          + "</font>"
          + android.text.format.Formatter.formatFileSize(SettingActivity.this,
              totalFileLen)));
    }

    @Override
    protected void onPostExecute(String result) {
      mWakeLock.release();
      mProgressDialog.dismiss();
      mProgressDialog = null;

      stopService(new Intent(SettingActivity.this, Net_Service.class));

      if (result == null || result.startsWith("Server")) {
        if (result != null)
          Toast.makeText(context, "Download error: " + result,
              Toast.LENGTH_LONG).show();
      } else // download successfully!
      {
        Toast
            .makeText(context, "File downloaded :" + result, Toast.LENGTH_LONG)
            .show();

        SharedPreferences prefs = getSharedPreferences(Constant.WELCOME_PAGE,
            Context.MODE_PRIVATE);
        prefs.edit().putBoolean(Constant.HAS_ILLUSTRATED, false).apply();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(result);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
            "application/vnd.android.package-archive");
        startActivity(intent);
      }
    }
  }

  @Override
  public void onPause() {
    super.onPause();
    // UmengUpdateAgent.setUpdateListener(null);
    LePreference.getInstance().save("floatWindowVisibility",
        mFloatWindowVisible);
  }

  @Override
  public void onResume() {
    super.onResume();
    mFloatWindowVisible = LePreference.getInstance().getBoolean(
        "floatWindowVisibility", true);

    mFloatWindowCheckBox.setChecked(mFloatWindowVisible);

    mFloatWindowCheckBox
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {

          @Override
          public void onCheckedChanged(CompoundButton buttonView,
              boolean isChecked) {

            mFloatWindowVisible = !mFloatWindowVisible;
            // Intent intent = new Intent(SettingActivity.this,
            // DeviceMonitorService.class);
            // if (mFloatWindowVisible) {
            // intent.putExtra("root_visiblity", FLOAT_WINDOW_VISIBLE);
            // } else {
            // intent.putExtra("root_visiblity", FLOAT_WINDOW_GONE);
            // }
            // startService(intent);

          }
        });

  }

  private void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory != null) {
      if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
          DeleteRecursive(child);
        }
      }
      if (fileOrDirectory.getAbsolutePath().endsWith(".mp4")
          || fileOrDirectory.getAbsolutePath().endsWith(".mp3")
          || fileOrDirectory.getAbsolutePath().endsWith(".lrc")) {
        fileOrDirectory.delete();
      }
    }
  }

  // clear cache
  private void clearCache() {
    File dir = getFilesDir();
    File file1 = new File(dir, Constant.TELL_STORY_SERACH_FILE);
    file1.delete();
    File file2 = new File(dir, Constant.PUSH_STORY_SERACH_FILE);
    file2.delete();
    CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
        SettingActivity.this).setTitle("提示").setMessage("确定清除本地缓存吗?")
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
          }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            // clear cache
            LeConfig.PlayMode = 2;

            LePreference.getInstance().delete(
                LePreference.PREFERNCE_TELLSTORY_CACHE);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_PUSHSTORY_CACHE);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_PUSHSLIDE_CACHE);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_BABYRADIO_CACHE);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_SUITCARTOON_CACHE);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_LAST_BABYRADIOSTAMP);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_LAST_SUITCARTOONTIMESTAMP);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_SHARERANK_CACHE);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_LAST_PUSHTIMESTAMP);
            LePreference.getInstance().delete(
                LePreference.PREFERNCE_NEXT_TIMESTAMP);

            clearTemplate();

            CacheManager.cleanApplicationData(SettingActivity.this, "");

            toastShow("已清除本地缓存");
            dialog.dismiss();

            try {
              String cacheSize = CacheManager
                  .getCacheSize(SettingActivity.this);
              tv_cachesize.setText(cacheSize);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });

    if (!isFinishing()) {
      cdb.create().show();
    }
  }

  private void clearTemplate() {
    new AsyncTask<Void, Void, Void>() {

      @Override
      protected void onPostExecute(Void arg0) {
        // toastShow("已清除下载的影音模板");
      }

      @Override
      protected Void doInBackground(Void... params) {

        DeleteRecursive(new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/haoduoai/"));

        String pkgPath = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/" + getPackageName();
        File pkgFile = new File(pkgPath);
        deleteDir(pkgFile);

        return null;
      }

    }.execute();
  }

  private boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
      String[] children = dir.list();
      if (children != null) {
        for (int i = 0; i < children.length; i++) {
          boolean success = deleteDir(new File(dir, children[i]));
          if (!success) {
            return false;
          }
        }
      }
    }
    // The directory is now empty so now it can be smoked
    return dir.delete();
  }

  private void clearTemplateCache() {
    CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
        SettingActivity.this).setTitle("提示").setMessage("确定清除下载的影音模板吗?")
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
          }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
            clearTemplate();
          }
        });

    if (!isFinishing()) {
      cdb.create().show();
    }
  }

}
